import re
from fastapi import Body
from pydantic import BaseModel, field_validator, Field
from typing import Optional
from core.exception.errors import ValidateError
from models.admin.user_model import AdminUserBase


# from models import AdminUserBase


class LoginIn(BaseModel):
    """
    登录schema
    """
    username: str = Field(..., example="kerrygao")
    password: str = Field(..., example="123456")

    @field_validator('username')
    def validator_username(cls, v):
        if not re.match(r"^[\w\-_.]{3,30}$", v):
            raise ValidateError(msg="用户名格式不正确")
        return v

    @field_validator('password')
    def validator_password(cls, v):
        if not re.match(r"^.{8,30}$", v):
            raise ValidateError(msg="密码格式不正确")
        return v


class Token(BaseModel):
    """
    返回token
    """
    token: str = Field(description="token", example="xxxxxxxxxxxxxxx")
    username: str = Field(description="用户名", example="kerrygao")
    avatar: Optional[str] = Field(description="用户头像", example="xxxxx", default=None)
    failure_time: int = Field(description="过期时间戳", example="1708585238")


class AdminUserRead(AdminUserBase):
    id: int


class AdminUserItem(AdminUserBase):
    id: int
    group_name: Optional[str] = None


class AdminUserCreate(AdminUserBase):
    password: str
    password_confirm: str

    @field_validator('password_confirm')
    def validator_password(cls, v, values):
        if not re.match(r"^.{8,30}$", v):
            raise ValidateError(msg="密码格式不正确")
        if 'password' in values.data and v != values.data['password']:
            raise ValidateError(msg="密码不一致")
        return v


class AdminUserUpdate(AdminUserCreate):
    id: int


class ChangePassword(BaseModel):
    """
    修改密码
    """
    old_password: str
    password: str
    confirm_password: str

    @field_validator('confirm_password')
    def validator_password(cls, v, values):
        if not re.match(r"^.{8,30}$", v):
            raise ValidateError(msg="密码格式不正确")
        if 'password' in values.data and v != values.data['password']:
            raise ValidateError(msg="密码不一致")
        return v


class SysLogQuery(BaseModel):
    """
    系统日志查询条件
    """
    ip: Optional[str] = None
    method: Optional[str] = None
    username: Optional[str] = None
